import React, { PureComponent } from 'react'
import {withRouter} from 'react-router-dom'
import { Modal} from 'antd'
import LinkButton from '../link-button'
import {formateDate} from '../../utils/utils'
import {reqWeather} from '../../api'
import { getUserInfo } from '../../utils/storage'
// import {menulist} from '../../assets/data/menulist'
import {connect} from 'react-redux'
import {logout} from '../../redux/actions'
import './index.scss'

class Header extends PureComponent {
  state = {
    currentTime: formateDate(Date.now()), // 当前时间字符串
    dayPictureUrl: 'https://img1.baidu.com/it/u=2839266329,2125997467&fm=26&fmt=auto', // 天气图片url
    weather: '', // 天气的文本
  }
  
  componentDidMount () {
    // 获取当前的时间
    this.getTime();
    // 获取当前天气
    this.getWeather();
  }

  /*
  当前组件卸载之前调用
   */
  componentWillUnmount () {
    // 清除定时器
    clearInterval(this.intervalId);
  }

  getTime = () => {
    // 每隔1s获取当前时间, 并更新状态数据currentTime
    this.intervalId = setInterval(() => {
      const currentTime = formateDate(Date.now());
      // console.log('currentTime: ', currentTime);
      this.setState({currentTime});
    }, 1000);
  }

  getWeather = async () => {
    // 调用接口请求异步获取数据
    const res = await reqWeather('珠海');
    // console.log('res: ', res);
    const {weather}=res;
    // 更新状态
    this.setState({weather});
  }

  /* getTitle=()=>{
    const path=this.props.location.pathname;
    let title;
    menulist.forEach(item=>{
      if(item.key===path){
        title=item.title;
      }else if(item.children){
        const v=item.children.find(v=>v.key===path);
        if(v){
          title=item.title+"-"+v.title;
        }
      }
    });
    return title;
  } */

  /*
  退出登陆
   */
  logout = () => {
    // 显示确认框
    Modal.confirm({
      cancelText:"取消",
      okText:"确定",
      content: '确定退出吗?',
      onOk: () => {
        // console.log('OK', this);
        this.props.logout();
        // deleteUserInfo();
        // this.props.history.replace("/login");
      }
    })
  }

  render() {
    const {currentTime, dayPictureUrl, weather} = this.state;
    const {username}=getUserInfo();
    const title = this.props.headTitle
    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎, {username}</span>
          <LinkButton onClick={this.logout}>退出</LinkButton>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span>{currentTime}</span>
            <img src={dayPictureUrl} alt="weather"/>
            <span>{weather}</span>
          </div>
        </div>
      </div>
    )
  }
}

export default connect(
  state => ({headTitle: state.headTitle, user: state.user}),
  {logout}
)(withRouter(Header))